package com.sike.netty.jinjie.eventloop.executor;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

@Slf4j
public class EventExecutorGroupTestClient {
    public static void main(String[] args) throws InterruptedException {
        // 新建 EventExecutorGroup 实例对象
        EventExecutorGroup executorGroup = new DefaultEventExecutorGroup(4);

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(new NioEventLoopGroup());
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new StringEncoder());
                ch.pipeline().addLast(executorGroup,new ChannelInboundHandlerAdapter(){
                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        log.info("客户端连接成功");
                        // 每隔 6 秒项服务端发送一条消息
                        ctx.executor().scheduleWithFixedDelay(new Runnable() {
                            @Override
                            public void run() {
                                String msg = "死磕 Netty 进阶 — 组件篇之 EventLoop;;" +
                                        LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                                log.info("客户端发送消息，{}",msg);

                                ctx.channel().writeAndFlush(msg);
                            }
                        },0,6, TimeUnit.SECONDS);
                    }
                });
            }
        });

        bootstrap.connect("127.0.0.1",8081).channel();
    }
}
